<?php
namespace App\Repository\Java;

use App\Repository\Contracts\GoodsInterface;
use App\Repository\Contracts\GoodsJavaInterface;
use Illuminate\Support\Facades\DB;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-02-06 13:39
 *
 * @Description:
 */
class GoodsRepository extends Repository implements GoodsJavaInterface
{
    protected function setPrefix()
    {
        $this->prefix = 'goods/';
    }

    public function syncInventory($storeId, array $data)
    {
        $data['storeId'] = $storeId;
        $result = $this->post(__FUNCTION__, $data);

        return $result['resultType'] === 'success';
    }

    public function syncList($createdAt = 0)
    {
        $page = 1;
        $rows = 10000;
        $form['updateDate'] = $createdAt;
        $result = $this->get(env('JAVA_RESOURCE').$this->prefix.'queryGoodsByConditionPaging.jhtml?page='.$page.'&rows='.$rows, $form);
        if ($result['total'] > 0) {
            foreach ($result['rows'] as $key => $val) {
                $insert = [];
                $update = [
                    'goods_id' => $val['id'], 'category_id' => $val['parentId'], 'article_no' => $val['articleNo'],
                    'bar_code' => $val['barCode'], 'zh_name' => $val['zhName'], 'en_name' => $val['enName'],
                    'mnemonic' => $val['mnemoni'], 'price' => round($val['storePrice'], 3), 'inventory' => 0,
                    'created_at' => strtotime($val['createDate']), 'updated_at' => strtotime($val['updateDate'])
                ];
                if (app(GoodsInterface::class)->detail($val['id'])) {
                    DB::table('goods')->where('goods_id', $val['id'])->update($update);
                    continue;
                }
                $insert[] = $update;
                if (!$key%1000) {
                    DB::table('goods')->insert($insert);
                } else {
                    DB::table('goods')->insert($insert);
                }
            }
        }

        return  true;
    }
}